package com.shengwei.truck.driver.view.ui.task;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.databinding.ScalePhotoBinding;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.vm.BaseViewModel;

import java.io.File;

import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 图片展示fragment
 */
public class PhotoViewFragment extends BaseFragment<BaseViewModel, ScalePhotoBinding> {
    String mPhotoUrl;
    String TAG = "PhotoViewFragment";
    private String mThumbUrl;
    private Handler mHandler;

    public static PhotoViewFragment newInstance(String photoUrl,String thumbUrl) {
        PhotoViewFragment fragment = new  PhotoViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString("photoUrl", photoUrl);
        bundle.putString("thumbUrl", thumbUrl);
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    public int getContentViewId() {
        return R.layout.scale_photo;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            mPhotoUrl = getArguments().getString("photoUrl");
            mThumbUrl = getArguments().getString("thumbUrl");
            Log.i(TAG,"mPhotoUrl="+mPhotoUrl+",mThumbUrl="+mThumbUrl);
        }
        createHandler();
        super.onCreate(savedInstanceState);
    }
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView =  super.onCreateView(inflater,container,savedInstanceState);
        //显示图片
        showPhoto();
        return rootView;
    }

    @Override
    public void onResume() {
        MyLogCat.i(TAG,"onResume");
        super.onResume();
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    /**
     * 创建handler
     */
    private void createHandler() {
        mHandler= new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    //从网络加载原图，比较大
                    showLoading("正在加载...");
                    loadPhoto();
                }
            }
        };
    }


    private void showPhoto() {
        //配置让图片可缩放
        PhotoViewAttacher attacher = new PhotoViewAttacher(mDataBinding.imvPhoto);
        attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                // ScalePhotoActivity.this.finish();
            }
        });
        //先显示一个模糊的缩略图，缩略图显示完毕后，再去下载原图
        getThumbUrLCache(mThumbUrl);
    }

    /**
     * 从缓存中取出缩略图，先加载缩略图
     * @param thumbUrl: 缩略图URL地址
     */
    public void getThumbUrLCache(String thumbUrl){
            new Thread(){
                public void run(){
                    try{
                        FutureTarget<File> future = Glide.with(mContext).downloadOnly().load(thumbUrl).into(500, 500);
                        File thumbUrlFile = future.get();
                        if (thumbUrlFile != null) {
                            String thumbUrlFilePath = thumbUrlFile.getAbsolutePath();
                            Bitmap bitmap = BitmapFactory.decodeFile(thumbUrlFilePath);
                            if (bitmap != null) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mDataBinding.imvPhoto.setVisibility(View.VISIBLE);
                                        mDataBinding.imvPhoto.setImageBitmap(bitmap);
                                        mHandler.sendEmptyMessage(0);
                                    }
                                });
                            }
                        }
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }.start();
    }


    /**
     * 加载原图
     */
    public void loadPhoto(){
        mDataBinding.imvPhotoOrigin.setVisibility(View.VISIBLE);
        PhotoViewAttacher attacher = new PhotoViewAttacher(mDataBinding.imvPhotoOrigin);
        attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                // ScalePhotoActivity.this.finish();
            }
        });
        MyLogCat.i(TAG,"mPhotoUrl="+mPhotoUrl);

        //加载原图optionRequestOptions options = new RequestOptions().override(Target.SIZE_ORIGINAL);
        RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA);    //只缓存的原图
        Glide.with(this)
                .load(mPhotoUrl)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        MyLogCat.i(TAG,"onResourceReady");
                        mDataBinding.imvPhoto.setVisibility(View.GONE);
                        dismissDlg();
                        return false;
                    }
                })
                .apply(options)
                .into(mDataBinding.imvPhotoOrigin);
    }
    /**
     * 先显示缩略图
     * @param type 0:加载缩略图，1加载原图
     */
    private void loadPhoto(int type) {
        RequestOptions options = null;
        String photoUrl = null;
        if(type == 0){
            mDataBinding.imvPhoto.setVisibility(View.VISIBLE);
            photoUrl = mThumbUrl;
            options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE);
            options.override(480,480);
        }
        else {
            mDataBinding.imvPhoto.setVisibility(View.GONE);
            mDataBinding.imvPhotoOrigin.setVisibility(View.VISIBLE);
            photoUrl = mPhotoUrl;
            options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA);
            options.override(480,480);

        }
        MyLogCat.i(TAG,"loadPhoto type="+type+",photoUrl="+photoUrl);
        Glide.with(this)
                .load(photoUrl)
                .apply(options)
                .listener(new RequestListener<Drawable>() {

                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        MyLogCat.i(TAG,"onLoadFailed onResourceReady type="+type);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if(type == 0){
                            MyLogCat.i(TAG,"onResourceReady type="+0);
                            mDataBinding.imvPhoto.setImageDrawable(resource);
                            mHandler.sendEmptyMessage(0);
                          //  loadPhoto(1);
                        }
                        else{
                            mDataBinding.imvPhotoOrigin.setImageDrawable(resource);
                            MyLogCat.i(TAG,"onResourceReady type="+1);
                            dismissDlg();
                        }
                        return true;
                    }
                })
                .into(type==0?mDataBinding.imvPhoto:mDataBinding.imvPhotoOrigin );
    }
}
